package com.zpark.cz.workfair;

import com.rabbitmq.client.*;
import com.zpark.cz.util.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer1 {
    private static final String QUEUE_NAME = "test-work_fair-queue";
    public static void main(String[] args) throws IOException, TimeoutException {
        // 获取连接及通道
        Connection conn = ConnectionUtil.getConnection();
        final Channel channel = conn.createChannel();
        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        // 同一时刻，服务器只会发送一条消息给一个消费者
        channel.basicQos(1);
        /**
         * 监听队列
         * 当监听到队列中有可获取的消息时，毁掉handleDelivery()方法，接收消息
         * 当第二个参数autoAck设置为false时，表示手动返回完成状态
        */
        channel.basicConsume(QUEUE_NAME, false, new
                DefaultConsumer(channel){
                    @Override
                    public void handleDelivery(String consumerTag, Envelope
                            envelope, AMQP.BasicProperties properties, byte[] body) throws
                            IOException {
                        String msg = new String(body, "utf-8");
                        System.out.println("消费者1：收到消息，msg -> " + msg);
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        // 设置为使用手动模式进行应答
                        channel.basicAck(envelope.getDeliveryTag(), false);
                    }
                });
    }
}
